package com.niiwoo.civet.trade.service.local.contract;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.account.constant.PlateformConstant;
import com.niiwoo.civet.trade.constant.AmountHandleConstant;
import com.niiwoo.civet.trade.dao.entity.FadadaContractTemplateFile;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectContract;
import com.niiwoo.civet.trade.service.local.contract.vo.BorrowerContractDTO;
import com.niiwoo.civet.trade.utils.SysNumberUtil;
import com.niiwoo.civet.user.dto.request.SimpleOrgInfo;
import com.niiwoo.civet.user.service.OrganizationDubboService;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.fadada.dto.request.GenerateContractRequestDTO;
import com.niiwoo.tripod.fadada.dto.response.FadadaResponseDTO;
import com.niiwoo.tripod.fadada.enums.SignClientRoleEnum;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 信息咨询服务协议
 *
 * @author liaojunjun
 */
@Service
public class InformationConsultingServiceProtocol extends AbstractFadadaContract {

    private static final Logger logger = LoggerFactory.getLogger(InformationConsultingServiceProtocol.class);

    @Reference(version = "1.0.0")
    private OrganizationDubboService organizationDubboService;

    @Autowired
    private PrivacyMasks privacyMasks;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private ContractBaseService contractBaseService;

    @Override
    public ProjectContract contractHandler(FadadaContractTemplateFile contractTemplate, String bizContractNo,
                                           Project project, String userId) throws Exception {
        logger.info("信息咨询服务协议处理开始... projectId:{}", project.getProjectId());

        // 构建信息查询授权书所需数据
        BorrowerContractDTO contractDTO = contractBaseService.getBorrowerContractDTO(project.getProjectId());
        contractDTO.setContractId(snowflakeIdWorker.nextId() + ""); //合同ID

        this.generateContract(contractTemplate, bizContractNo, contractDTO, project);

        ProjectContract result = this.signContract(contractTemplate, contractDTO, project);

        this.contractFilling(contractDTO.getContractId());

        logger.info("信息咨询服务协议处理结束... projectId:{}", project.getProjectId());

        return result;
    }

    private void generateContract(FadadaContractTemplateFile contractTemplate, String bizContractNo, BorrowerContractDTO borrower, Project project) throws Exception {
        logger.info("信息咨询服务协议生成开始... projectId:{}", project.getProjectId());

        GenerateContractRequestDTO dto = new GenerateContractRequestDTO();
        dto.setContractId(borrower.getContractId());
        dto.setDocTitle(contractTemplate.getTemplateName());
        dto.setTemplateId(contractTemplate.getTemplateId());

        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("contractNo", bizContractNo);
        parameterMap.put("borrowerName", borrower.getBorrowerUserName());
        parameterMap.put("borrowerIdCard", privacyMasks.maskIdCardSixTwo(borrower.getBorrowerIdCard()));
        parameterMap.put("borrowerAddress", borrower.getBorrowerAddress());
        parameterMap.put("borrowAmount", SysNumberUtil.amountChineseFormat(project.getContractAmount().toString()));
        parameterMap.put("deadLine", project.getDeadline().toString());
        parameterMap.put("projectTitle", project.getTitle().replaceAll("借款用途：","").replaceAll("借款用于",""));

        parameterMap.put("investRate", project.getBorrowRate().multiply(new BigDecimal(AmountHandleConstant.HUNDRED))
                .setScale(AmountHandleConstant.CALCULATE_PRECISION_TWO, BigDecimal.ROUND_HALF_EVEN).toString());
        parameterMap.put("consultingServiceFee", project.getConsultingFee()
                .setScale(AmountHandleConstant.CALCULATE_PRECISION_TWO, BigDecimal.ROUND_HALF_EVEN).toString());

        parameterMap.put("niiwooReditCode", privacyMasks.maskInstitutionalReditCode(PlateformConstant.NIIWOO_REDIT_CODE));
        parameterMap.put("signDate", DateFormatUtils.format(new Date(), "yyyy年MM月dd日"));
        dto.setParameterMap(parameterMap);

        // 签章列表
        List<List<String>> signatureNamesList = new ArrayList<>();

        // 签章信息
        String antiGuaranteeSignatureNamesText = "                甲方（签章）：" + borrower.getBorrowerUserName();
        List<String> antiGuaranteeSignatureNamesCells = new ArrayList<>();
        antiGuaranteeSignatureNamesCells.add(antiGuaranteeSignatureNamesText);
        signatureNamesList.add(antiGuaranteeSignatureNamesCells);

        // 签章信息
        String guaranteeSignatureNamesText = "                乙方（签章）：深圳市你我他信息咨询有限公司";
        List<String> guaranteeSignatureNamesCells = new ArrayList<>();
        guaranteeSignatureNamesCells.add(guaranteeSignatureNamesText);
        signatureNamesList.add(guaranteeSignatureNamesCells);

        List<String> headers = new ArrayList<>();
        headers.add("");
        // 所有人签名 在pdf合同模板的keyword下面插入(正好在页尾，不用留空白)，需要留够空白，不然会覆盖下面的内容
        GenerateContractRequestDTO.DynamicTable signNameTable = new GenerateContractRequestDTO.DynamicTable();
        signNameTable.setInsertWay(1);
        signNameTable.setKeyword("自甲方向乙方支付服务费后，本协议终止。");
        signNameTable.setCellHeight(60f);
        signNameTable.setHeaders(headers);
        // 签名时需要增加高度并居中显示
        signNameTable.setCellVerticalAlignment(5);
        signNameTable.setDatas(signatureNamesList);
        signNameTable.setBorderFlag(false);
        List<GenerateContractRequestDTO.DynamicTable> tables = new ArrayList<>();
        tables.add(signNameTable);

        dto.setDynamicTables(tables);

        generateContract(dto);

        logger.info("信息咨询服务协议生成结束... projectId:{}", project.getProjectId());
    }

    private ProjectContract signContract(FadadaContractTemplateFile contractTemplate, BorrowerContractDTO borrower, Project project) throws Exception {
        logger.info("法大大合同自动签署-信息咨询服务协议 projectId:{}", project.getProjectId());

        // 借款人签署
        FadadaResponseDTO fadadaResponse = null;
        String transactionId = snowflakeIdWorker.nextId() + "";
        String docTitle = borrower.getBorrowerUserName() + "的信息咨询服务协议_" + borrower.getContractId();
        String borrowerSignKeyword = "甲方（签章）：" + borrower.getBorrowerUserName();
        fadadaResponse = extSignAuto(transactionId, borrower.getContractId(), borrower.getFadadaCacertId(),
                SignClientRoleEnum.BORROWER.getValue(), docTitle, borrowerSignKeyword);
        logger.info("法大大合同自动签署-信息咨询服务协议 借款人签署结束... projectId:{}", project.getProjectId());

        // 你我他平台签署
        SimpleOrgInfo guarantee = organizationDubboService.getByOrgId(project.getOrgId());
        if(guarantee == null){
            logger.error("信息咨询服务协议处理异常 guarantee is null. orgId:{}, projectId:{}", project.getOrgId(), project.getProjectId());
            throw new BizException("TRD10005", "极速借借款合同处理异常 guarantee is null");
        }

        transactionId = snowflakeIdWorker.nextId() + "";
        String platformSignKeyword = "乙方（签章）：深圳市你我他信息咨询有限公司";
        fadadaResponse = extSignAuto(transactionId, borrower.getContractId(), guarantee.getFadadaCacertId(),
                SignClientRoleEnum.PLATFORM.getValue(), docTitle, platformSignKeyword);
        logger.info("法大大合同自动签署-信息咨询服务协议 平台签署结束... projectId:{}", project.getProjectId());

        return this.buildContractUpdateRecord(contractTemplate.getTemplateId(), borrower.getContractId(), transactionId,
                fadadaResponse.getViewUrl(), fadadaResponse.getDownloadUrl());
    }

}
